import {XgPlayer} from "../index";
import fScreen from "fscreen";

export class XgControlFullScreen {
  root!: HTMLElement;
  fullScreen = false;
  constructor(private player: XgPlayer) {
    this.init();
  }
  private init() {
    this.root = document.createElement('div');
    this.root.className = 'control-icon-wrap fullscreen-wrap';
    this.root.innerHTML = `<svg class="icon icon-control-player" aria-hidden="true">
                              <use xlink:href="#icon-fullscreen"></use>
                            </svg>`;

    this.root.addEventListener('click', this.handleToggleFullScreen.bind(this));
    this.player.container.addEventListener('fullscreenchange', () => {
      this.changeIcon(!!document.fullscreenElement);
    });
  }
  private changeIcon(fullScreen: boolean) {
    if (this.fullScreen !== fullScreen) {
      this.fullScreen = fullScreen;
    }
    const iconSvg = this.root.getElementsByTagName('use')[0];
    if (iconSvg) {
      const type = fullScreen ? 'quxiaoquanping' : 'fullscreen';
      iconSvg.setAttribute('xlink:href', '#icon-' + type);
    }
  }
  private handleToggleFullScreen() {
    this.fullScreen = !this.fullScreen;
    if (fScreen.fullscreenEnabled) {
      if (this.fullScreen) {
        fScreen.requestFullscreen(this.player.container);
      } else {
        fScreen.exitFullscreen();
      }
    }
  }
}
